package com.haitaoit.chengquan.main;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.baiduservice.LocationInfoModel;
import com.haitaoit.chengquan.baiduservice.LocationService;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.versions.UpdateManagerUtils;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final int PHOTO_PERMISS = 123;
    private LocationService locationService;
    private static final int          MY_PERMISSIONS_REQUEST_CALL_CAMERA = 2;
    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    private              List<String> mPermissionList                    = new ArrayList<>();
    private              String[]     permissions                        = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };
    private UpdateManagerUtils mUpdateManagerUtils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        locationService = new LocationService(this);
        locationService.registerListener(mListener);
        locationService.start();// 定位SDK
        initPerMission();
    }

    private void initPerMission() {
        mPermissionList.clear();
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);

            } else {

                if (TextUtils.equals(permissions[i], Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                } else if (TextUtils.equals(permissions[i], Manifest.permission.READ_PHONE_STATE)) {
                    // 检查版本更新
                    mUpdateManagerUtils = new UpdateManagerUtils(MainActivity.this);
                    mUpdateManagerUtils.checkUpdate();
                }
            }
        }
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            Toast.makeText(MainActivity.this, "已经授权", Toast.LENGTH_LONG).show();
        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(MainActivity.this, permissions, MY_PERMISSIONS_REQUEST_CALL_CAMERA);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_CAMERA) {
            for (int i = 0; i < grantResults.length; i++) {

                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    //判断是否勾选禁止后不再询问
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permissions[i]);
                    if (TextUtils.equals(permissions[i], Manifest.permission.ACCESS_FINE_LOCATION)) {
                        if (showRequestPermission) {
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0);
                        }
                    } else {
                        if (showRequestPermission) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            //        Uri uri = Uri.fromParts("package", context.getPackageName());
                            //        intent.setData(uri);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            startActivity(intent);
                        }
                    }
                } else {

                    if (TextUtils.equals(permissions[i], Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    } else if (TextUtils.equals(permissions[i], Manifest.permission.READ_PHONE_STATE)) {
                        // 检查版本更新
                        mUpdateManagerUtils = new UpdateManagerUtils(MainActivity.this);
                        mUpdateManagerUtils.checkUpdate();

                    }
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private BDLocationListener mListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {// 定位成功
                Log.e("tag", location.getCity() + "===" + location.getStreet() + "===" + location.getLatitude());
                LocationInfoModel cityInfo = LocationInfoModel.getInstance();
                cityInfo.setCity(location.getCity());
                cityInfo.setLatitude(location.getLatitude());
                cityInfo.setLontitude(location.getLongitude());
                if (location.getCity() != null && location.getCity().trim().length() > 0) {
                    ToastUtils.showToast("定位城市：" + location.getCity());
                }
                PreferenceUtils.setPrefString("location_city", location.getCity());
                // 定位成功 停止定位服务
                locationService.unregisterListener(mListener);// 注销掉监听
                locationService.stop();// 停止定位服务
            } else {// 定位失败
                PreferenceUtils.setPrefString("location_city", "上海市");
                ToastUtils.showToast("定位失败 默认为上海市");
            }
        }


    };

    @Override
    protected void onDestroy() {
        locationService.unregisterListener(mListener); // 注销掉监听
        locationService.stop(); // 停止定位服务
        //销毁handler
        mUpdateManagerUtils.onDestroyDoing();

        super.onDestroy();
    }

    //        //添加6.0新权限
    //        private void requestPhotoPermiss() {
    //            PermissionGen.with(this)
    //                    .addRequestCode(PHOTO_PERMISS)
    //                    .permissions(
    //                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    //                            Manifest.permission.READ_PHONE_STATE,
    //                            Manifest.permission.READ_CALENDAR,
    //                            Manifest.permission.CAMERA,
    //                            Manifest.permission.BODY_SENSORS,
    //                            Manifest.permission.ACCESS_COARSE_LOCATION,
    //                            Manifest.permission.READ_EXTERNAL_STORAGE,
    //                            Manifest.permission.RECORD_AUDIO
    //                    )
    //                    .request();
    //        }
    //
    //        @Override
    //        public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
    //            PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    //        }
    //
    //        @PermissionSuccess(requestCode = PHOTO_PERMISS)
    //        public void requestPhotoSuccess() {
    //
    //
    //        }
    //
    //        @PermissionFail(requestCode = PHOTO_PERMISS)
    //        public void requestPhotoFail() {
    //
    //
    //        }


}
